package com.immunology.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.immunology.core.BaseDao;
import com.immunology.core.BaseTransformer;
import com.immunology.core.GenericDao;
import com.immunology.database.DbColumns;
import com.immunology.model.MedicineCard;

public class MedicineCardDao extends BaseDao<MedicineCard> implements
		GenericDao<MedicineCard> {

	public MedicineCardDao(BaseTransformer<MedicineCard> transformer) {
		super(transformer, new String("MEDICINE_CARD"));
	}

	@Override
	public void insert(MedicineCard medicineCard) {
		Connection connection = connectionManager.getConnection();
		StringBuilder query = new StringBuilder();
		query.append("INSERT INTO ");
		query.append(tableName);
		query.append(" (PATIENT_ID, CREATION_DATE, OTHER_PATIENT_INFO) ");
		query.append(" VALUES(?, ?, ?)");
		try {
			PreparedStatement preparedStatementstmt = (PreparedStatement) connection
					.prepareStatement(query.toString());
			preparedStatementstmt.setInt(DbColumns.FIRST_COLUMN,
					medicineCard.getPatientId());
			preparedStatementstmt.setDate(DbColumns.SECOND_COLUMN,
					medicineCard.getCreationDate());
			preparedStatementstmt.setString(DbColumns.THIRD_COLUMN,
					medicineCard.getOtherPatientInfo());
			preparedStatementstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			connectionManager.closeConnection(connection);
		}
	}

	@Override
	public void update(int id, MedicineCard medicineCard) {

	}

	public MedicineCard searchMedicineCardByPatientId(int id) {
		Connection connection = connectionManager.getConnection();
		MedicineCard medicineCard = new MedicineCard();
		ResultSet resultSet = null;
		Statement statement = null;
		StringBuilder query = new StringBuilder();
		query.append("SELECT * FROM ");
		query.append(tableName);
		query.append(" WHERE PATIENT_ID =" + id);
		try {
			statement = connection.createStatement();
			resultSet = statement.executeQuery(query.toString());
			while (resultSet.next()) {
				medicineCard.setId(resultSet.getInt(DbColumns.FIRST_COLUMN));
				medicineCard.setPatientId(resultSet
						.getInt(DbColumns.SECOND_COLUMN));
				medicineCard.setCreationDate(resultSet
						.getDate(DbColumns.THIRD_COLUMN));
				medicineCard.setOtherPatientInfo(resultSet
						.getString(DbColumns.FOURTH_COLUMN));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			connectionManager.closeConnection(connection);
		}
		return medicineCard;
	}

}
